const path = require('path');

// 条件性加载插件，仅在需要时使用
let BundleAnalyzerPlugin;
if (process.env.ANALYZE === 'true') {
  try {
    BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
  } catch (e) {
    console.warn('webpack-bundle-analyzer not installed, skipping bundle analysis');
  }
}

module.exports = {
  /**
   * webpack配置优化
   */
  webpack: {
    /**
     * 配置别名，简化导入路径
     */
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@components': path.resolve(__dirname, 'src/components'),
      '@pages': path.resolve(__dirname, 'src/pages'),
      '@hooks': path.resolve(__dirname, 'src/hooks'),
      '@services': path.resolve(__dirname, 'src/services'),
      '@contexts': path.resolve(__dirname, 'src/contexts'),
      '@utils': path.resolve(__dirname, 'src/utils'),
      '@types': path.resolve(__dirname, 'src/types')
    },

    /**
     * 性能优化配置
     */
    performance: {
      hints: process.env.NODE_ENV === 'production' ? 'warning' : false,
      maxEntrypointSize: 512000, // 512KB
      maxAssetSize: 512000, // 512KB
    },

    /**
     * 优化配置
     */
    optimization: {
      /**
       * 代码分割配置
       */
      splitChunks: {
        chunks: 'all',
        cacheGroups: {
          // 第三方库分组
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendors',
            chunks: 'all',
            priority: 10,
          },
          // React相关库
          react: {
            test: /[\\/]node_modules[\\/](react|react-dom|react-router-dom)[\\/]/,
            name: 'react',
            chunks: 'all',
            priority: 20,
          },
          // Ant Design组件库
          antd: {
            test: /[\\/]node_modules[\\/]antd[\\/]/,
            name: 'antd',
            chunks: 'all',
            priority: 15,
          },
          // 工具库
          utils: {
            test: /[\\/]node_modules[\\/](axios|lodash|dayjs)[\\/]/,
            name: 'utils',
            chunks: 'all',
            priority: 5,
          },
          // 公共业务代码
          common: {
            name: 'common',
            minChunks: 2,
            chunks: 'all',
            priority: 0,
            reuseExistingChunk: true,
          }
        }
      },
      /**
       * 运行时优化
       */
      runtimeChunk: {
        name: 'runtime',
      }
    },

    /**
     * 插件配置
     */
    plugins: {
      /**
       * 添加包分析器（仅在ANALYZE=true时）
       */
      add: process.env.ANALYZE === 'true' && BundleAnalyzerPlugin ? [
        new BundleAnalyzerPlugin({
          analyzerMode: 'static',
          reportFilename: 'bundle-report.html',
          openAnalyzer: false,
        })
      ] : [],

      /**
       * 配置现有插件
       */
      configure: (plugins) => {
        return plugins;
      }
    },

    /**
     * 模块配置
     */
    module: {
      rules: [
        /**
         * 图片优化
         */
        {
          test: /\.(png|jpe?g|gif|svg)$/i,
          type: 'asset/resource',
          generator: {
            filename: 'images/[hash][ext][query]'
          }
        },
        /**
         * 字体优化
         */
        {
          test: /\.(woff|woff2|eot|ttf|otf)$/i,
          type: 'asset/resource',
          generator: {
            filename: 'fonts/[hash][ext][query]'
          }
        }
      ]
    }
  },

  /**
   * 开发服务器配置
   */
  devServer: {
    port: 3001,
    hot: true,
    open: true,
    compress: true,
    historyApiFallback: true,
    /**
     * 代理配置
     */
    proxy: {
      '/api': {
        target: 'http://localhost:6001',
        secure: false,
        changeOrigin: true,
        logLevel: 'debug',
        ws: true,
        pathRewrite: {
          '^/api': '/api'
        },
        onError: (err, req, res) => {
          console.log('Proxy Error:', err);
        },
        onProxyReq: (proxyReq, req, res) => {
          console.log('Proxy Request:', req.method, req.url);
        }
      }
    },
    /**
     * 性能优化配置
     */
    client: {
      overlay: {
        errors: true,
        warnings: false
      },
      logging: 'warn'
    }
  },

  /**
   * Jest配置优化
   */
  jest: {
    configure: (jestConfig) => {
      jestConfig.setupFilesAfterEnv = [
        '<rootDir>/src/setupTests.ts',
        ...jestConfig.setupFilesAfterEnv
      ];
      jestConfig.moduleNameMapper = {
        '^@/(.*)$': '<rootDir>/src/$1',
        '^@components/(.*)$': '<rootDir>/src/components/$1',
        '^@pages/(.*)$': '<rootDir>/src/pages/$1',
        '^@hooks/(.*)$': '<rootDir>/src/hooks/$1',
        '^@services/(.*)$': '<rootDir>/src/services/$1',
        '^@contexts/(.*)$': '<rootDir>/src/contexts/$1',
        '^@utils/(.*)$': '<rootDir>/src/utils/$1',
        '^@types/(.*)$': '<rootDir>/src/types/$1',
        ...jestConfig.moduleNameMapper
      };
      return jestConfig;
    }
  }
};